import asyncio
import logging
import uvicorn
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from config import config, get_database, close_database

from models.base import BaseModel
from models.sleep_monitoring import SleepMonitoringRecord, Room
from controller.room_controller import RoomController
from controller.sleep_monitoring_controller import SleepMonitoringController
from controller.tcp_data_controller import router as tcp_router
from service.room_service import RoomService
from service.sleep_monitoring_service import SleepMonitoringService

from service.tcp_data_service import get_tcp_data_service
from service.memory_cache_service import get_memory_cache

# Configure logging
logging.basicConfig(
    level=getattr(logging, config.LOG_LEVEL),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler(config.LOG_FILE) if config.LOG_FILE else logging.NullHandler()
    ]
)

logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan manager"""
    # Startup
    logger.info(f"Starting {config.APP_NAME} v{config.APP_VERSION}")
    
    # Initialize database
    try:
        database = get_database()
        database.connect()
        logger.info("Database connected successfully")
        
        # Create tables if they don't exist
        SleepMonitoringRecord.create_table_if_not_exists()
        Room.create_table_if_not_exists()
        logger.info("Database tables created successfully")
        
        # Create default room if it doesn't exist
        try:
            if not Room.select().where(Room.room_id == 'default-room').exists():
                Room.create(
                    room_id='default-room',
                    name='默认房间',
                    description='系统默认房间',
                    is_active=True
                )
                logger.info("Default room created successfully")
        except Exception as e:
            logger.warning(f"Failed to create default room: {e}")
        
    except Exception as e:
        logger.error(f"Failed to connect to database: {e}")
        raise
    

    
    yield
    
    # Shutdown
    logger.info("Shutting down application")
    

    
    # Close database connection
    try:
        close_database()
        logger.info("Database connection closed")
    except Exception as e:
        logger.error(f"Error closing database connection: {e}")

# Create FastAPI application
app = FastAPI(
    title="EEG Signal Dispatcher",
    description="脑波信号分发系统 - 接收、处理和分发脑波数据",
    version="2.0.0",
    lifespan=lifespan
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure this properly for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize services
room_service = RoomService()
sleep_monitoring_service = SleepMonitoringService()


# Initialize TCP services (these are singleton functions, not coroutines)
memory_cache = get_memory_cache()
tcp_data_service = get_tcp_data_service()

# Initialize controllers
room_controller = RoomController()
sleep_monitoring_controller = SleepMonitoringController()

# Global exception handler
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    logger.error(f"Global exception handler caught: {exc}")
    return JSONResponse(
        status_code=500,
        content={"success": False, "message": "Internal server error", "detail": str(exc)}
    )

# Health check endpoint
@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {
        "success": True,
        "message": "Service is healthy",
        "app_name": config.APP_NAME,
        "version": config.APP_VERSION,

    }

# Root endpoint
@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "success": True,
        "message": "EEG Signal Dispatcher API",
        "version": "2.0.0",
        "status": "running",
        "features": [
            "房间管理",
            "睡眠监测会话",
            "实时脑波数据处理",
            "原始数据存储",

        ]
    }

# API Info endpoint
@app.get("/info")
async def api_info():
    """API information endpoint"""
    return {
        "success": True,
        "data": {
            "app_name": config.APP_NAME,
            "version": config.APP_VERSION,
            "description": config.APP_DESCRIPTION,

            "database": {
                "host": config.DB_HOST,
                "port": config.DB_PORT,
                "name": config.DB_NAME
            }
        }
    }

# 注册路由
app.include_router(room_controller.router)
app.include_router(sleep_monitoring_controller.router)
app.include_router(tcp_router)  # TCP数据API路由

if __name__ == "__main__":
    # Create logs directory if it doesn't exist
    import os
    log_dir = os.path.dirname(config.LOG_FILE)
    if log_dir and not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    # Run the application
    uvicorn.run(
        "main:app",
        host=config.API_HOST,
        port=config.API_PORT,
        reload=config.API_RELOAD,
        log_level=config.LOG_LEVEL.lower(),
        access_log=True
    )